<template>
  <el-dialog
    :model-value="show"
    title="新增用户权限"
    width="1000px"
    append-to-body
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    class="system-user-edit-dialog form-label-80"
  >
    <div class="conntet-box" v-loading="basicLoading">
      <div class="content-left">
        <div class="form-title">用户信息</div>
        <div class="form-box-readonly">
          <div class="form-item-readonly">
            <span class="form-label-readonly">用户ID：</span>
            <span class="form-value-readonly">
              {{ detailForm.id || DEFAULT_TEXT }}
            </span>
          </div>
          <div class="form-item-readonly">
            <span class="form-label-readonly">登录账号：</span>
            <span class="form-value-readonly">
              {{ detailForm.account || DEFAULT_TEXT }}
            </span>
          </div>
          <div class="form-item-readonly">
            <span class="form-label-readonly">姓名：</span>
            <span class="form-value-readonly">
              {{ detailForm.name || DEFAULT_TEXT }}
            </span>
          </div>
          <div class="form-item-readonly">
            <span class="form-label-readonly">钉钉ID：</span>
            <span class="form-value-readonly">
              {{ detailForm.ding_id || DEFAULT_TEXT }}
            </span>
          </div>
          <div class="form-item-readonly">
            <span class="form-label-readonly">联系电话：</span>
            <span class="form-value-readonly">
              {{ detailForm.phone || DEFAULT_TEXT }}
            </span>
          </div>
          <div class="form-item-readonly">
            <span class="form-label-readonly">邮箱：</span>
            <span class="form-value-readonly">
              {{ detailForm.email || DEFAULT_TEXT }}
            </span>
          </div>
          <!-- <div class="form-item-readonly">
            <span class="form-label-readonly">员工状态：</span>
            <span class="form-value-readonly">
              <span v-if="detailForm.actived === true">已激活</span>
              <span v-else-if="detailForm.actived === false">未激活</span>
              <span v-else>{{ DEFAULT_TEXT }}</span>
            </span>
          </div> -->
        </div>
      </div>
      <div class="content-right">
        <div class="form-title">权限信息</div>
        <el-form
          ref="detailFormRef"
          :model="detailForm"
          :rules="rules"
          label-width="70px"
          class="form-box user-edit-form-box"
          v-loading="loading"
          v-if="!detailForm.isDelete"
        >
          <div class="user-edit-form-info">
            <div class="user-add-form-item">
              <el-form-item
                label="当前公司："
                prop="gongsi"
                style="width: 100%"
              >
                {{ userStore().company_name || DEFAULT_TEXT }}
              </el-form-item>
              <el-form-item
                label="团队："
                prop="group_ids"
                :rules="{
                  type: 'array',
                  required: true,
                  message: '请选择团队',
                  trigger: 'change'
                }"
                style="width: 100%"
              >
                <el-cascader
                  v-model="detailForm.group_ids"
                  :options="options"
                  :props="teamProps"
                  :show-all-levels="false"
                  :size="detailForm.group_ids?.length ? 'small' : undefined"
                />
              </el-form-item>
            </div>
            <el-button type="danger" plain @click="detailForm.isDelete = true">
              移除用户
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
    <template #footer>
      <el-button
        type="primary"
        :loading="submitLoading"
        :disabled="!show"
        @click="submitApply"
      >
        提交
      </el-button>
      <el-button type="info" @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { DEFAULT_TEXT } from '@/utils/const';
import userStore from '@/store/modules/user';
import {
  companyGroupAll,
  companyUserBind,
  companyUserRemove,
  companyUserDetail
} from '@/api/system';
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  activeRow: {
    type: Object,
    default: () => {}
  }
});

const emit = defineEmits();

const teamProps = reactive({
  emitPath: false,
  checkStrictly: true,
  multiple: true,
  value: 'id',
  label: 'name',
  children: 'childs'
});

// 关闭
function handleClose() {
  emit('update:show', false);
}

// 提交
const detailFormRef = ref();
const submitLoading = ref(false);
async function submitApply() {
  try {
    const _detailForm = detailForm.value;
    if (!_detailForm.isDelete) {
      await detailFormRef.value.validate();
      submitLoading.value = true;
      companyUserBind({
        users: [
          {
            id: _detailForm.id,
            name: _detailForm.name,
            group_ids: _detailForm.group_ids
          }
        ]
      })
        .then(() => {
          $msg.success('编辑用户权限成功');
          emit('success');
          handleClose();
        })
        .finally(() => {
          submitLoading.value = false;
        });
      return;
    }

    submitLoading.value = true;
    companyUserRemove({ id: _detailForm.id })
      .then(() => {
        $msg.success('移除用户成功');
        emit('success');
        handleClose();
      })
      .finally(() => {
        submitLoading.value = false;
      });
  } catch {
    console.log('用户管理-编辑用户提交校验未通过');
  }
}

// 规则
const rules = reactive({});

// 获取团队
const options = ref([]);
const loading = ref(false);
function getOptions() {
  loading.value = true;
  companyGroupAll()
    .then(res => {
      options.value = res.data || [];
      deepOptions(options.value);
    })
    .finally(() => {
      loading.value = false;
    });
}

function deepOptions(list) {
  list.forEach(item => {
    // if (!item.available) item.disabled = true;
    if (item.childs?.length) deepOptions(item.childs);
  });
}

// 初始化表单
const detailForm = ref({});
const basicLoading = ref(false);
watch(
  () => props.show,
  val => {
    if (!val) return;
    // 赋默认值
    getOptions();
    detailForm.value = { group_ids: [] };
    basicLoading.value = true;
    companyUserDetail({ id: props.activeRow.id })
      .then(res => {
        const resData = res.data || {};
        detailForm.value = resData;
        detailForm.value.group_ids = (
          detailForm.value.groups ||
          props.activeRow.groups ||
          []
        ).map(item => item.id);
      })
      .finally(() => {
        basicLoading.value = false;
      });
  }
);
</script>

<style lang="scss" scoped>
.conntet-box {
  display: flex;
  height: 100%;
}
.content-left {
  width: 300px;
  display: flex;
  flex-direction: column;
  height: 100%;
  :deep(.organize-tree) {
    flex: 1;
  }
}
.content-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  :deep(.el-form) {
    overflow-y: auto;
  }
}
.user-add-form-item {
  width: calc(100% - 110px);
  border: 1px dashed #dfdfdf;
  margin-top: 20px;
  padding: 20px 30px 10px 20px;
  box-sizing: border-box;
  &:first-child {
    margin-top: 10px;
  }
}
.form-item-readonly {
  width: 100% !important;
}
.user-edit-form-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

<style>
.system-user-edit-dialog .el-dialog__body {
  height: 65vh;
}
</style>
